<!--
  智慧社区管理系统 - 投诉建议表单页面
  @author Wu.Liang
  @date 2025-01-27
-->
<template>
  <div class="complaint-form-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">{{ isEdit ? '编辑投诉建议' : '新建投诉建议' }}</h2>
      <div class="page-actions">
        <el-button @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '保存修改' : '提交投诉' }}
        </el-button>
      </div>
    </div>

    <!-- 表单内容 -->
    <el-card class="form-card" shadow="never">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投诉标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入投诉标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投诉分类" prop="categoryId">
              <el-select
                v-model="formData.categoryId"
                placeholder="请选择投诉分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属社区" prop="communityId">
              <el-select
                v-model="formData.communityId"
                placeholder="请选择社区"
                @change="handleCommunityChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房户信息" prop="householdId">
              <el-select
                v-model="formData.householdId"
                placeholder="请选择房户"
                style="width: 100%"
                :disabled="!formData.communityId"
              >
                <el-option
                  v-for="item in householdList"
                  :key="item.id"
                  :label="item.roomNumber"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select
                v-model="formData.priority"
                placeholder="请选择优先级"
                style="width: 100%"
              >
                <el-option label="低" :value="1" />
                <el-option label="普通" :value="2" />
                <el-option label="高" :value="3" />
                <el-option label="紧急" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="匿名投诉">
              <el-switch v-model="formData.isAnonymous" />
              <span class="form-tip">开启后将隐藏投诉人信息</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="投诉内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述投诉内容..."
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="联系方式" prop="contactInfo" v-if="!formData.isAnonymous">
          <el-input
            v-model="formData.contactInfo"
            placeholder="请输入联系方式（手机号/邮箱）"
          />
        </el-form-item>

        <el-form-item label="上传图片">
          <el-upload
            v-model:file-list="fileList"
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :limit="5"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息..."
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 编辑模式下的额外字段 -->
        <template v-if="isEdit">
          <el-divider content-position="left">处理信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="处理人员" prop="assigneeId">
                <el-select
                  v-model="formData.assigneeId"
                  placeholder="请选择处理人员"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in assigneeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计解决时间" prop="estimatedResolveTime">
                <el-date-picker
                  v-model="formData.estimatedResolveTime"
                  type="datetime"
                  placeholder="请选择预计解决时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="处理状态" prop="status">
                <el-select
                  v-model="formData.status"
                  placeholder="请选择处理状态"
                  style="width: 100%"
                >
                  <el-option label="待处理" :value="0" />
                  <el-option label="处理中" :value="1" />
                  <el-option label="已解决" :value="2" />
                  <el-option label="已关闭" :value="3" />
                  <el-option label="已驳回" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '保存修改' : '提交投诉' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { showError, showSuccess } from '@/utils/message'
import { 
  Plus, 
  Check, 
  ArrowLeft,
  Search,
  Refresh
} from '@element-plus/icons-vue'
import type { Complaint, CreateComplaintParams, UpdateComplaintParams } from './types/complaint'
import { complaintApi, complaintCategoryApi } from '@/api/complaint'
import { commonApi } from '@/api/property'

// 作者: Wu.Liang

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const submitting = ref(false)
const formRef = ref()
const isEdit = computed(() => !!route.params.id)

// 表单数据
const formData = reactive<CreateComplaintParams & UpdateComplaintParams>({
  title: '',
  content: '',
  categoryId: undefined,
  communityId: undefined,
  householdId: undefined,
  priority: 2,
  isAnonymous: false,
  contactInfo: '',
  remark: '',
  // 编辑模式字段
  assigneeId: undefined,
  estimatedResolveTime: undefined,
  status: undefined
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入投诉标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择投诉分类', trigger: 'change' }
  ],
  communityId: [
    { required: true, message: '请选择所属社区', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入投诉内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '内容长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' }
  ]
}

// 下拉选项数据
const categoryList = ref<any[]>([])
const communityList = ref<any[]>([])
const householdList = ref<any[]>([])
const assigneeList = ref<any[]>([])

// 文件上传相关
const fileList = ref<any[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 生命周期
onMounted(() => {
  loadCategoryList()
  loadCommunityList()
  loadAssigneeList()
  
  if (isEdit.value) {
    loadComplaintDetail()
  }
})

// 加载投诉分类列表
const loadCategoryList = async () => {
  try {
    const response = await complaintCategoryApi.getCategoryList()
    if (response.code === 200) {
      categoryList.value = response.data
    }
  } catch (error) {
    console.error('加载投诉分类失败:', error)
  }
}

// 加载社区列表
const loadCommunityList = async () => {
  try {
    const response = await commonApi.getCommunityList()
    if (response.code === 200) {
      communityList.value = response.data
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
  }
}

// 加载房户列表
const loadHouseholdList = async (communityId: number) => {
  try {
    const response = await commonApi.getHouseholdList({ communityId })
    if (response.code === 200) {
      householdList.value = response.data
    }
  } catch (error) {
    console.error('加载房户列表失败:', error)
  }
}

// 加载处理人员列表
const loadAssigneeList = async () => {
  try {
    // 这里需要后端提供获取处理人员列表的接口
    assigneeList.value = [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' },
      { id: 3, name: '王五' }
    ]
  } catch (error) {
    console.error('加载处理人员列表失败:', error)
  }
}

// 加载投诉详情
const loadComplaintDetail = async () => {
  try {
    const complaintId = Number(route.params.id)
    const response = await complaintApi.getComplaintDetail(complaintId)
    if (response.code === 200) {
      Object.assign(formData, response.data)
      if (formData.communityId) {
        loadHouseholdList(formData.communityId)
      }
    }
  } catch (error) {
    console.error('加载投诉详情失败:', error)
    showError('加载投诉详情失败')
  }
}

// 事件处理
const handleCommunityChange = (communityId: number) => {
  formData.householdId = undefined
  householdList.value = []
  if (communityId) {
    loadHouseholdList(communityId)
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    if (isEdit.value) {
      const complaintId = Number(route.params.id)
      const response = await complaintApi.updateComplaint(complaintId, formData)
      if (response.code === 200) {
        showSuccess('修改成功')
        handleBack()
      } else {
        showError(response.message || '修改失败')
      }
    } else {
      const response = await complaintApi.createComplaint(formData)
      if (response.code === 200) {
        showSuccess('提交成功')
        handleBack()
      } else {
        showError(response.message || '提交失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    showError('提交失败')
  } finally {
    submitting.value = false
  }
}

const handleReset = () => {
  formRef.value.resetFields()
  fileList.value = []
}

const handleBack = () => {
  router.push('/complaint/list')
}

// 文件上传相关方法
const handleRemove = (file: any, fileList: any[]) => {
  console.log(file, fileList)
}

const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    showError('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    showError('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.complaint-form-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.text-muted {
  color: #909399;
}
</style> 